package com.example.tetris;
import android.media.MediaPlayer;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;


import com.example.manager.GameCenter;
import com.example.tetris.databinding.ActivityMainBinding;

public class MainActivity extends AppCompatActivity {
    private ActivityMainBinding mBinding;
    private MediaPlayer backgroundMusic;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding = ActivityMainBinding.inflate(getLayoutInflater());
        //com.example.tetris.databinding.ActivityMainBinding mBinding = ActivityMainBinding.inflate(getLayoutInflater());
        //上式是绑定类视图的系统提供的一种更安全的本地写法，等同于在override之前先private ActivityMainBinding mBinding;
        setContentView(mBinding.getRoot());

        GameCenter.defaultCenter.bingView(mBinding.previewView,mBinding.gameView);

        GameCenter.defaultCenter.start();

        backgroundMusic = MediaPlayer.create(this, R.raw.tetris_player);
        backgroundMusic.setLooping(true); // 设置循环播放

        initEvent();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (backgroundMusic != null && backgroundMusic.isPlaying()) {
            backgroundMusic.pause();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if ( backgroundMusic != null && !backgroundMusic.isPlaying()) {
            backgroundMusic.start();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (backgroundMusic != null) {
            backgroundMusic.release();
            backgroundMusic = null;
        }
    }

    private void initEvent() {
        mBinding.left.setOnClickListener(v -> {
            GameCenter.defaultCenter.moveLeft();
        });
        mBinding.right.setOnClickListener(v -> {
            GameCenter.defaultCenter.moveRight();
        });
        mBinding.down.setOnClickListener(v -> {
            GameCenter.defaultCenter.moveDown();
        });
        mBinding.start.setOnClickListener(v -> {

            GameCenter.defaultCenter.startAutoMoveDown();


                mBinding.start.setImageResource(R.drawable.pause); // 切换为停止图标
                mBinding.start.setContentDescription("暂停");

                // 开始播放背景音乐
                if (backgroundMusic != null && !backgroundMusic.isPlaying()) {
                    backgroundMusic.start();
            }
//                else {  // 如果没有在自动下落
//                //GameCenter.defaultCenter.stopAutoMoveDown();
//                mBinding.start.setImageResource(R.drawable.play); // 切换为开始图标
//                mBinding.start.setContentDescription("开始");
//
//            }
        });
        mBinding.rotate.setOnClickListener(v -> {
            GameCenter.defaultCenter.rotate();
        });
    }

}